/**
 * Cropper v3.0.0
 */
$.get('/static/admins/lib/cropper/cropper.js?v=1');
layui.link('/static/admins/lib/cropper/cropper.css');
layui.define(['jquery', 'layer','upload'], function (exports) {
    var $ = layui.jquery;
    var layer = layui.layer;
    var upload = layui.upload;
    var c = {
        lockUp : false, // 上传过程中加锁
        imageObject : '', // 存放图片的img对象
        uploadInst : '',  // upload 上传图片对象
        uploadData : {'width':0,'height':0,'imgx':0,'imgy':0},       // 剪切数据
    }
    var sc = c;
    
    var html = '<div class="layui-container" style="width: 600px; padding: 2px;">'  
        +'<input type="file" id="JP_file" style="display: none;"  />'
        +' <div class="layui-row" >'
        +'    <div class="layui-col-md9" id="JP_img_main" >'
        +'        <img style="width: 100%;" src="http://admins.elite.com/uploads/default/2019/05/05/a3/5cce5d57010bb.png" />'
        +'    </div>'
        +'    <div class="layui-col-md3" id="JP_img_preview" style="padding: 0px 10px;">'
        +'        <div class="p-preview JP_img_previewOne" style="width: 100%; height: 100px;overflow: hidden"></div>'
        +'        <div class="p-preview" style="width: 100%; margin-top: 40px;font-size: 11px;color: #666;">双击右边图片可切换拖动图片或选择框<br/>滚动鼠标可以放大缩小图片</div>'
        +'    </div>'
        +'</div>'
        +'<div class="layui-form-item" style="margin-top:2px;margin-bottom:2px; margin-left:0px" >'
        +'    <div class="layui-btn-group" id="JP_btn_main">'
        +'        <button type="button" class="layui-btn" crop-event="rotate" data-option="90" >正旋转90度</button>'
        +'        <button type="button" class="layui-btn" crop-event="rotate" data-option="-90" >逆旋转90度</button>'
        +'        <button type="button" class="layui-btn" crop-event="reset" >重置图片</button>'
        //+'        <button type="button" class="layui-btn" crop-event="change" >重选图片</button>'
        +'        <button type="button" class="layui-btn" crop-event="saveData" >保存结果</button>'
        +'        <button type="button" class="layui-btn" crop-event="close" >取消</button>'
        +'    </div>'
        +' </div>'        
        +'</div>';
        
    //关闭按钮
    var closeView = function(){
        $('#JP_img_main img').cropper('destroy');
        layer.closeAll();
    }
    // 按钮操作
    var clickEvent = function(){  
        $("body").delegate("#JP_btn_main .layui-btn","click",function(e){
            var event = $(this).attr("crop-event");
            if( event === 'change' ){ // 重新选择图片 
                $('#JP_file').click();
                var clock = false;
                $('#JP_file').change(function () {
                    if( clock == true ) return true;
                    clock = true;
                    var Reader = new FileReader();
                    var file = this.files[0];
                    Reader.readAsDataURL(file);
                    Reader.onload = function (e) { 
                        c.imageObject.cropper('destroy').attr('src', this.result).cropper(c.croConfig);
                        //c.imageObject.cropper('replace',this.result);//.replace(this.result);//.cropper(c.croConfig);
                    };
                });
               // closeView();
               // $(sys.elem).click();
            }else if(event === 'close'){ // 关闭
                closeView();       
            }else{
                //  if( ! c.imageObject ) alert( '请先选择图片');
                if( event === 'saveData'){ // 保存图片
                    if( c.lockUp === true ) return false;
                    c.lockUp = true;
                    var data = c.imageObject.cropper("getCroppedCanvas", {
                        width: sys.saveW,
                        height: sys.saveH
                    });                
                    
                    if( sys.blob &&  typeof data.toBlob == 'function' ){
                        data.toBlob(function (blob) {
                            var fd = new FormData();
                            fd.append("file", blob,'image.png');
                            fd.append("type", sys.data.type);
                            
                            var xmlHttp = new XMLHttpRequest();                    
                            xmlHttp.onreadystatechange = function (){
                                if (xmlHttp.readyState === 4) {
                                    if (xmlHttp.status === 304 || (xmlHttp.status >= 200 && xmlHttp.status < 300)) {
                                        if( typeof sys.done == 'function' ){
                                            var ret =  eval("("+xmlHttp.responseText+")");
                                            sys.done(ret);
                                            closeView();
                                        }
                                    } else {
                                        if( typeof sys.error == 'function' ){
                                            sys.error(xmlHttp.statusText);
                                        }
                                    }
                                }else{
                                    console.log('readyState:' + xmlHttp.readyState);
                                }
                            }
                            
                            xmlHttp.open('POST', sys.url, true);
                            xmlHttp.send(fd);
                        });
                    }else{                                                
                        var cronData = c.imageObject.cropper('getData');
                        c.uploadInst.config.data = {
                            'width' : cronData.width,
                            'height': cronData.height,
                            'imgx'  : cronData.x,
                            'imgy'  : cronData.y,
                            'rotate': cronData.rotate,
                            'type'  : sys.data.type
                        };
                        c.uploadInst.upload();
                    }
                                
                }if( event === 'reset'){   // 重置选择
                    c.imageObject.cropper('reset');
                }else if (event === 'rotate') {
                    var option = $(this).attr('data-option');
                    c.imageObject.cropper('rotate', option);
                }
            }
        });
    };
    
    
    // 剪切图片处理
    var cropperDeal = function(imageObject){
        c.lockUp = false;
        c.croConfig = {
            aspectRatio: sys.saveW / sys.saveH ,
            preview: $(".JP_img_previewOne"),
            strict:true,
            autoCropArea:1, //自动剪裁的区域大小
            crop: function(e) {
            },            
            built: function () {
                console.log('built');
            }
        };
        imageObject.cropper(c.croConfig);
    }
    
    // 显示剪切的界面
    var showCropper = function (imgFile){    
        closeView();
        var openbox = layer.open({
            skin:'layui-layer-admin',//layui-layer-lan', // layui-layer-molv
            offset: '10px',
           // closeBtn:0,
            title: "图片裁剪",
            type: 1,
            content: html,//'aaaa',
            area: '600px',
            success: function () {
                //image.cropper(options);                
                c.imageObject = $('#JP_img_main img');
                c.imageObject.attr('src',imgFile);
                clickEvent();
                cropperDeal(c.imageObject);
            },
            cancel: function (index) {      
                closeView();
            }
        });
    }
    
    //初始化上传图片
    var uploadAction = function (e){
        if( typeof e.type != 'undefined' ) e.data.type = e.type;
        c.uploadInst = upload.render({
            elem : e.elem, //绑定元素
            url  : e.url, //上传接口
            data : e.data,    
            auto : false, // 取消选择文件后自动上传
            //bindAction　: '#JS_c_bindAction', // 绑定触发上传的按钮                    
            choose : function (obj){ // 选择文件之后处理  
                obj.preview(function(index, file, result){
                    showCropper(result);
                });
            },
            before: function(obj){ //上传文件之前的回调
                //$.extend(c.uploadInst.config.data,c.uploadData);
            },
            done:function(ret){
                closeView();
                sys.done(ret);
            },
            error:function(){
                closeView();
                sys.error(ret);
            }
        });
    };
        
    // 对外调用方法
    var myCropper = {        
        render: function (e){
            $.extend(sys,e);
            //执行实例
            uploadAction(sys);
            //showCropper();
            
        }
    }
        
    var sys = {
        saveH : 200, // 剪切后保存图片的 高度
        saveW : 200, // 剪切后保存图片的 宽度
        url   : '/sys/Upload/image', // 上传接口
        data  : {'type':'default'},
        blob  : false,
        done  : function(){},  //上传成功后回调        
        error : function(msg){
            layer.open({
                skin:'layui-layer-admin',
                shade: 0,
                closeBtn:0,
                offset: 't',
                anim: 3,
                time: 3000,
                title: '信息',
                content: msg
            });            
        }, //上传失败的回调
    }
    
    
    exports('uploadimg', myCropper);
});